import re, sys, getopt

#srt_format_str = '''
# {id}
# {start_formatedtimestr} --> {end_formatedtimestr}
# 在经历了一场人生巨变之后
# When I was lying there in the VA hospital ...
#
# '''
# voicetext_abspath = '/Users/apple/Downloads/202010281732237307.txt'
voicetext_line_reg = '\[\d+:\d+\.\d+,\d+:\d+\.\d+\]\s+[^\n]+'
rawtimestr_reg = '(\d+):(\d+)\.(\d+)'

def ensure_twobit_digit(digit):
    digit = str(digit)
    if len(digit) == 0:
        digit = '00'
    if len(digit) == 1:
        digit = '0' + digit
    if len(digit) > 2:
        raise (FooError('''Too long digit: {} got , can only convert 0,1,2 bit digit, please check...'''.format(digit)))
    return digit

def ensure_threebit_digit(digit):
    digit = str(digit)
    if len(digit) == 0:
        digit = '000'
    if len(digit) == 1:
        digit = '00' + digit
    if len(digit) == 2:
        digit = '0' + digit
    if len(digit) > 3:
        raise (FooError('''Too long digit: {} got , can only convert 0,1,2,3 bit digit, please check...'''.format(digit)))
    return digit

def minute_to_hour_and_minute_str(minute):
    minute = int(minute)
    hour = str(minute / 60)
    minute = str(ensure_twobit_digit(minute % 60))
    return "{}:{}".format(hour, minute)

class FooError(Exception):
    pass

def rawtimestr_to_formatedtimestr(rawtimestr_tuple, need_little_increase=False):
    rawminute,second,millisecond  = rawtimestr_tuple
    # timestr_group = re.search(rawtimestr_reg, rawtimestr)
    # if timestr_group is None:
    #     raise(FooError('23-23 function:::rawtimestr_to_formatedtimestr got invalid rawtimestr, timestr_reg: {} not match rawtimest: {}'.format(rawtimestr_reg, rawtimestr)))
    # else:
    #     rawminute = timestr_group.group(1)
    #     second = timestr_group.group(2)
    #     millisecond = timestr_group.group(3)
    # hour_minute_str = minute_to_hour_and_minute_str(rawminute)
    rawminute = int(rawminute)
    hour = int(rawminute / 60)
    minute = int(rawminute) % 60
    second = int(second)
    millisecond = int(millisecond)
    # second = ensure_twobit_digit(second)
    if need_little_increase:
        millisecond += 100
        # millisecond = ensure_threebit_digit(int(millisecond) + 100)  # 传言如果上一条字幕的结束时间与当前条字幕的结束时间拉不开差距就会造成字幕导入到此终止
        # millisecond = int(millisecond)
        if millisecond >= 1000:
            millisecond -= 1000
            second += 1
            if second >= 60:
                second -= 60
                minute += 1
                if minute >= 60:
                    minute -= 60
                    hour += 1
    hour = str(hour)
    minute = ensure_twobit_digit(minute)
    second = ensure_twobit_digit(second)
    millisecond = ensure_threebit_digit(millisecond)
    formated_timestr = '{}:{}:{},{}'.format(hour, minute, second, millisecond)
    return formated_timestr


def convert_voicetext_content_into_srt_content(voicetext_conent):
    voicetext_line_list = re.findall(voicetext_line_reg, voicetext_conent)
    print(voicetext_line_list)
    srt_content = ''
    for index,voicetext_line in enumerate(voicetext_line_list):
        rawtimestr_list = re.findall(rawtimestr_reg, voicetext_line)
        start_rawtimestr_tuple = rawtimestr_list[0]
        print('41-41 function:::convert_voicetext_content_into_srt_content:: start_rawtimestr_tuple:', start_rawtimestr_tuple)
        end_rawtimestr_tuple = rawtimestr_list[1]
        print('43-43 function:::convert_voicetext_content_into_srt_content:: end_rawtimestr_tuple:', end_rawtimestr_tuple)
        if index == 0:
            start_formatedtimestr = rawtimestr_to_formatedtimestr(start_rawtimestr_tuple)
        else:
            start_formatedtimestr = rawtimestr_to_formatedtimestr(start_rawtimestr_tuple, need_little_increase=True)
        end_formatedtimestr = rawtimestr_to_formatedtimestr(end_rawtimestr_tuple)

        text_reg = '\]\s+([^\n]+)'
        text_group = re.search(text_reg, voicetext_line)
        if text_group is None:
            raise(FooError('48-48 function:::convert_voicetext_content_into_srt_content got invalid voicetext_line:: voicetext_line: {} , text_reg: {}'.format(voicetext_conent, text_reg)))
        else:
            text = text_group.group(1)
            id = str(index + 1)
            unit_srt_str = '''{id}
{start_formatedtimestr} --> {end_formatedtimestr}
{text}

'''.format(
                id=id,
                start_formatedtimestr=start_formatedtimestr,
                end_formatedtimestr=end_formatedtimestr,
                text=text,
            )
            srt_content += unit_srt_str
    # print()
    return srt_content


def convert_tencent_voicetext_into_srt(voicetext_abspath, output_abspath):
    with open(voicetext_abspath, 'r', encoding='utf-8') as f:
        voicetext_conent = f.read()
    srt_content = convert_voicetext_content_into_srt_content(voicetext_conent)
    output_abspath = './srt.srt'
    # output_abspath = './srt.txt'
    with open(output_abspath, 'w', encoding='utf-8') as f:
        f.write(srt_content)
    print('76-76 ', srt_content, '...srt_content, output_abspath: ', output_abspath)

def print_help_and_exit():
    print('python3 convert_tencent_voicetext_into_srt.py -p <voicetext_abspath>')
    sys.exit(2)

if __name__ == '__main__':
    output_abspath = './srt.srt'
    argv = sys.argv[1:]
    try:
        opts, args = getopt.getopt(argv, "hp:", ["voicetext_abspath="])
    except getopt.GetoptError:
        print_help_and_exit()
        # print('convert_tencent_voicetext_into_srt.py -p <voicetext_abspath>')
        # sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print_help_and_exit()
            # print('convert_tencent_voicetext_into_srt.py -p <voicetext_abspath>')
            # sys.exit()
        elif opt in ("-p", "--voicetext_abspath"):
            voicetext_abspath = arg
    if(len(argv) == 0):
        voicetext_abspath = './202010281732237307.txt'
        # print('convert_tencent_voicetext_into_srt.py -p <voicetext_abspath>')
        # print_help_and_exit()
    convert_tencent_voicetext_into_srt(voicetext_abspath, output_abspath)

    # with open(voicetext_abspath, 'r', encoding='utf-8') as f:
    #     voicetext_conent = f.read()
    # srt_content = convert_voicetext_content_into_srt_content(voicetext_conent)
    # # srt_path = './srt.srt'
    # srt_path = './srt.txt'
    # with open(srt_path, 'w', encoding='utf-8') as f:
    #     f.write(srt_content)
    # print('76-76 ', srt_content, '...srt_content')
